package org.jef.idempotency.aspect;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.jef.security.service.PigUser;
import org.jef.security.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @description: aop实现幂等性处理
 * @author: ChengZhi 0336
 * @create: 2024-08-28 14:16
 **/
@Aspect
@Slf4j
@Component
public class IdempotencyHandle {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 配置文件中配置幂等过期时间
     */
    @Value("${idempotency.expireTime}")
    private Long expireTime;

    @Around("@annotation(org.jef.idempotency.annotation.Idempotency)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 请求的URI
        String uri = request.getRequestURI();
        // 请求的IP
        String clientIp = ServletUtil.getClientIP(request);
        // 获取请求方式
        String requestMethod = request.getMethod();
        // 获取携带参数
        final Enumeration parameterNames = request.getParameterNames();
        StringBuilder stringBuilder = new StringBuilder();
        while (parameterNames.hasMoreElements()) {
            String key = (String) parameterNames.nextElement();
            String parameter = request.getParameter(key);
            stringBuilder.append(key).append("=").append(parameter).append("&");
        }
        // 当前subject
        PigUser user = SecurityUtils.getUser();
        Long userId = 0L;
        if (user != null) {
            userId = user.getId();
        }

        // 构建redis key
        String redisKey = clientIp + uri + requestMethod + stringBuilder + userId;
        redisKey = "IDEMPOTENCY_" + md5(redisKey);
        // 检查redis是否存在当前记录，存在即返回false，不存在即返回true
        Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, "",expireTime, TimeUnit.SECONDS);
        //如果存在，表示已经请求过了，直接抛出异常，由全局异常进行处理返回指定信息
        if (ifAbsent != null && !ifAbsent) {
            throw new IllegalArgumentException("请勿重复提交！");
        }
        return pjp.proceed();
    }

    private static String md5(String str) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] s = md5.digest(str.getBytes());
            String ss= "";
            String result = "";
            for (int i = 0; i < s.length; i++) {
                ss = Integer.toHexString(s[i] & 0xff);
                if (ss.length() == 1) {
                    result += "0" + ss;
                } else {
                    result += ss;
                }
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            log.error("get md5 error", e);
        }
        return null;
    }

}
